package com.stary.music.api.source.kuwo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.stary.music.api.vo.MusicInfo;
import com.stary.music.exception.MyMusicException;
import com.stary.music.util.HTTPUtils;
import com.stary.music.util.PropertiesUtils;

/**
 * 酷我音乐API
 * @author stary
 * @date 2018年6月14日 下午2:47:11
 */
public class KuWoMusic {

	private static final Logger logger=LoggerFactory.getLogger(KuWoMusic.class);
	private static final String PREFIX="kuwo.music";	
	private static PropertiesUtils pUtils=null;	 
	static {
		pUtils=new PropertiesUtils();
		pUtils.setKeyPrefix(PREFIX);
	}
	/**
	 * 根据关键词搜索歌曲信息 <br>
	 * 关键词：歌曲名、专辑、歌手 
	 * @param searchRequest
	 * @return
	 */
	public List<MusicInfo> searchMusicList(KuWoSearchRequest searchRequest){
		if(searchRequest.getAll()==null || searchRequest.getAll().isEmpty()){
			logger.error("缺少参数或出现不能识别的参数");
			throw new MyMusicException("a parameter is missing or unrecognized");
		}
		List<MusicInfo> list=null;
		StringBuffer buffer=new StringBuffer();
		JSONObject searchRequestJSON=(JSONObject) JSONObject.toJSON(searchRequest);
		for (Entry<?, ?> entry : searchRequestJSON.entrySet()) {
			buffer.append("&" + entry.getKey() + "=" + entry.getValue());
		}
		buffer.replace(0, 1, "");
		logger.debug("搜索歌曲信息入参----->>{}",buffer.toString());
		pUtils.setKey("search");
		try {
			String resp=HTTPUtils.sendGet(pUtils.getStringValue(), buffer.toString());
			logger.debug("搜索歌曲信息出参----->>{}",resp);
			if(!resp.isEmpty()){
				JSONObject respJSON = JSONObject.parseObject(resp);
				if(respJSON.containsKey("abslist")){
					JSONArray abslistJSONArray = respJSON.getJSONArray("abslist");
					list=new ArrayList<MusicInfo>();
					MusicInfo info=null;
					for (int i = 0; i < abslistJSONArray.size(); i++) {
						String song=abslistJSONArray.getString(i);
						JSONObject songJSON = JSONObject.parseObject(song);
						info=new MusicInfo();
						// 歌名
						String name=songJSON.getString("NAME");
						info.setName(name);
						// 歌手
						String singer=songJSON.getString("ARTIST");
						info.setSinger(singer);
						// 专辑
						String album=songJSON.getString("ALBUM");
						info.setAlbum(album);
						// MID
						String rid=songJSON.getString("MUSICRID");
						info.setMid(rid);
						// ID
						String id=rid.split("MUSIC_")[1];
						info.setId(id);
						// 歌曲外链
						
						// 歌曲详情信息
						pUtils.setKey("info");
						try {
							String xml=HTTPUtils.sendGet(pUtils.getStringValue(), "rid="+rid );
							logger.debug("歌曲详情信息出参----->>{}",xml);
							if(!xml.isEmpty()){								
								String cover  = xml.split("<artist_pic240>")[1].split("</artist_pic240>")[0];						
								info.setCover(cover);		
								// 加密歌词歌词
								//String lyric  = xml.split("<lyric>")[1].split("</lyric>")[0];	
//								if(!src.contains(".acc") || !src.contains(".mp3")){
//									src="http://"+xml.split("<aacdl>")[1].split("</aacdl>")[0]+"/resource/"+xml.split("<aacpath>")[1].split("</aacpath>")[0];
//									info.setSrc(src);
//								}
								if(searchRequest.getShowLrc()!=0){
									//歌词 
									String lyric = getMusicLyric(id);
									info.setLyric(lyric);
								}
								
																		
							}
						} catch (Exception e) {
							logger.error("获取歌曲信息出现异常",e);
						}
						list.add(info);	
					}
				}
			}
		} catch (Exception e) {
			logger.error("搜索歌曲信息出现异常",e);
		}
		return list;
	}
	/**
	 * 获取歌词外链
	 * @param mid
	 * @return
	 */
	public String getMusicSrc(String mid){
		String src="";
		pUtils.setKey("src");
		try {
			src=HTTPUtils.sendGet(pUtils.getStringValue(), "type=convert_url&rid="+mid+"&format=aac|mp3&response=url");			
		} catch (Exception e) {
			logger.error("动态获取外链出现异常",e);
		}
		return src;
	}
	public static String getMusicLyric(String id){
		String lyric="";
		// 从pc播放页面获取歌词
		pUtils.setKey("playpage");
		try {
			String playHtml = HTTPUtils.sendGet(pUtils.getStringValue().replace("ID", id), "");
			if (!playHtml.isEmpty() && playHtml.contains("var lrcList = ")) {
				//logger.debug("播放页面出参----->>{}",playHtml);
				String[] lrcList = playHtml.split("var lrcList = \\[");
				if(lrcList.length>1){
					String lrc = lrcList[1].split("]")[0];
					if(!lrc.isEmpty() || lrc!=""){
						lrc = "[" + lrc + "]";		
						JSONArray lrcJSONArray=JSONArray.parseArray(lrc);
						StringBuffer buffer=new StringBuffer("");
						for (int j = 0; j < lrcJSONArray.size(); j++) {
							String lrcs=lrcJSONArray.getString(j);
							JSONObject lrcsJSON=JSONObject.parseObject(lrcs);
							String time=lrcsJSON.getString("time");
							String[] times=time.split("\\.");
							time="["+secondToMinute(Integer.parseInt(times[0]))+"."+ (times[1].length()>2 ? times[1].substring(0,2) : times[1]) +"]";
							String lineLyric=lrcsJSON.getString("lineLyric");
							buffer.append(time+lineLyric+"\n");																	
						}
						lyric=buffer.toString(); 					
					}
				}
				
				
			}
		} catch (Exception e) {
			logger.error("获取歌词出现异常",e);
		}
		return lyric;
	}
	/**
	 * 秒钟数转换成分钟数格式  01:05
	 * @param second
	 * @return
	 */
	private static String secondToMinute(int second){	
		int s=second % 60;
		int m= second/60;
		String ss= s<10 ? "0"+s : s+"";
		String mm=m<10 ? "0"+m : m+"";	
		return mm+":"+ss;
	}	
}
